<template>
  <el-dialog
    :title="dialogTitle"
    class="putarea"
    :visible.sync="syncDialogArea"
    :before-close="handleClosed"
    width="860px"
  >
    <div class="putarea__table">
      <el-table :data="areaList" border style="width: 100%">
        <el-table-column
          prop="name"
          header-align="center"
          label="线路"
          width="160"
        >
        </el-table-column>
        <el-table-column label="区域" header-align="center">
          <template slot-scope="scope">
            <div
              v-for="(aquera, qIndex) in scope.row.list"
              :key="qIndex"
              class="putarea__row--item"
            >
              <el-checkbox
                :indeterminate="aquera.isIndeterminate"
                v-model="aquera.checkAll"
                :disabled="
                  (currentLineId !== '-1' &&
                    scope.row.id !== currentLineId &&
                    scope.row.id !== '-1') ||
                    (currentLineId === '-1' && scope.row.id === '-1')
                "
                class="putarea__checkbox"
                @change="handleCheckAllChange(1, aquera)"
              >
              </el-checkbox>
              <span class="putarea__row--aname" :title="aquera.name">{{
                aquera.name
              }}</span>
              <el-popover placement="button" width="180" trigger="click">
                <div
                  v-for="(area, aInd) in aquera.list"
                  :key="aInd"
                  class="putarea__row--popover"
                >
                  <el-checkbox
                    class="putarea__checkbox"
                    :disabled="
                      (currentLineId !== '-1' &&
                        scope.row.id !== currentLineId &&
                        scope.row.id !== '-1') ||
                        (currentLineId === '-1' && scope.row.id === '-1')
                    "
                    @change="handleCheckAllChange(2, aquera)"
                    v-model="area.isChosen"
                  >
                  </el-checkbox
                  >{{ area.name }}
                </div>
                <el-button type="text" slot="reference">
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-checkbox
      class="putarea__checkbox putarea__checkAll"
      @change="handleCheckAllChange(3)"
      :indeterminate="areaCheckAll.isIndeterminate"
      v-model="areaCheckAll.checkAll"
    >
    </el-checkbox
    >全选
    <div v-if="dialogType == 2" class="putarea__newarea">
      新增区域默认投放
      <el-checkbox
        class="putarea__checkbox putarea__newarea--chechbox"
        v-model="autoStatue"
      >
      </el-checkbox>
    </div>
    <p v-if="dialogType == 2">
      创建新的区域（区）时，商品默认投放到该区域（小区）。
    </p>
    <div class="putarea__diatf">
      <el-button
        @click="
          handleClosed(() => {
            syncDialogArea = false;
          })
        "
        >取 消</el-button
      >
      <el-button @click="areasIsReady" type="primary">确 定 </el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
// import { getShipperLinePoints } from "@/api/rection/index";
import { PoiontList } from "./interface";
import {
  Vue,
  Component,
  Prop,
  Emit,
  Watch,
  PropSync,
} from "vue-property-decorator";

@Component({})
export default class PutArea extends Vue {
  @Prop({ default: [] })
  areaList: PoiontList[];

  /**
   * 业务类型
   * 1: 来自配送线路
   * 2: 来自配送设置
   * 3: 小区设置
   */
  @Prop({ default: 0 })
  dialogType: number;

  @Prop({ default: "" })
  currentLineId: string;

  /** 0-团长 1-提货点 */
  @Prop({ default: 1 })
  isPointSet: number;

  /** 设置投放区域弹框 */
  @PropSync("dialogArea", { type: Boolean, default: false })
  syncDialogArea: boolean;

  /** 投放点百分比 */
  @PropSync("goodPointIdsPercentage", { type: String })
  syncGoodPointIdsPercentage: string;

  /** 新增点是否自动推送 */
  @PropSync("autoShippingState", { default: false })
  syncAutoShippingState: any;

  autoStatue = false;

  /** 最外成全选状态修改 */
  areaCheckAll = {
    checkAll: false,
    isIndeterminate: false,
  };

  @Watch("syncAutoShippingState")
  onAutoShippingStateChange(val: any) {
    this.autoStatue = val;
  }

  @Watch("areaList", { immediate: true, deep: true })
  onAreaListChange(val: any) {
    this.reasetSelectStatus(val);
  }

  /** 抛出已选中的提货点ID */
  @Emit("areaIsReady")
  emitAreaChoosed(data) {
    return data;
  }

  get dialogTitle() {
    let title = "";
    switch (this.dialogType) {
      case 1:
        title = "提货点设置";
        break;
      case 2:
        title = "投放区域";
        break;
      case 3:
        title = "小区设置";
    }
    return title;
  }

  /**
   * 关闭弹窗的回调
   */
  handleClosed(done) {
    this.$confirm("确定要退出该页面? 退出后，未保存的信息将不会保留!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        if (this.dialogType === 2) {
          this.autoStatue = this.syncAutoShippingState;
        }
        done();
      })
      .catch(() => {
        console.log("取消了关闭弹窗");
      });
  }

  /**
   * 描述 选择操作
   * @param {Number} type 1:区域多选编辑 2:区域下的街道 3:最外层全选操作
   * @param {Number、Object} item 当前对象
   */
  handleCheckAllChange(type, item) {
    switch (type) {
      case 1:
        this.changeAreaCheckAll(item);
        break;
      case 2:
        this.changeAreaCheckItem(item);
        break;
      case 3:
        this.changeAreaListAll();
        break;
    }
    this.reasetSelectStatus(this.areaList);
  }

  /**
   * 重置各个多选的选择状态
   */
  reasetSelectStatus(val) {
    let count = 0;
    let flag = 0;
    let list = [];
    let tempList = [];
    if (this.currentLineId === "-1") {
      tempList = val.filter(i => i.id === "-1");
      list = val.filter(i => i.id !== "-1");
    } else {
      tempList = val.filter(i => i.id !== this.currentLineId && i.id !== "-1");
      list = val.filter(i => i.id === this.currentLineId || i.id === "-1");
    }
    this.setListDisabled(tempList);
    list.forEach(i => {
      i.isChosen = Boolean(i.isChosen === 1 || i.isChosen === true);
      i.disabeld = false;
      this.changeAreaCheckAll(i);
      i.list.forEach(t => {
        t.isChosen = Boolean(t.isChosen === 1 || t.isChosen === true);
        t.disabeld = false;
        this.changeAreaCheckItem(t);
        t.list.forEach(d => {
          d.isChosen = Boolean(d.isChosen === 1 || d.isChosen === true);
          d.disabeld = false;
          t.checkAll = true;
          flag++;
          if (d.isChosen === 1 || d.isChosen === true) {
            count++;
          } else {
            t.checkAll = false;
          }
        });
      });
    });
    this.areaList = val;
    this.reasetAllSelect({ flag, count });
  }

  /**
   * 设置非当前编辑的线路不可操作
   */
  setListDisabled(list) {
    list.forEach(i => {
      i.isChosen = false;
      i.disabeld = true;
      this.changeAreaCheckAll(i);
      i.list.forEach(t => {
        t.isChosen = false;
        t.disabeld = true;
        this.changeAreaCheckItem(t);
        t.list.forEach(d => {
          d.isChosen = false;
          d.disabeld = true;
          t.checkAll = false;
        });
      });
    });
  }

  resetListChoosed(list) {
    list.forEach(i => {
      i.isChosen = false;
      i.disabeld = false;
      i.list.forEach(t => {
        t.isChosen = false;
        t.disabeld = false;
        t.list.forEach(d => {
          d.isChosen = false;
          d.disabeld = false;
          t.checkAll = false;
        });
      });
    });
  }

  /**
   * 重置最外层全选操作
   */
  reasetAllSelect({ flag, count }) {
    if (flag && count === flag) {
      this.areaCheckAll.checkAll = true;
      this.areaCheckAll.isIndeterminate = false;
    } else if (count && count < flag) {
      this.areaCheckAll.checkAll = false;
      this.areaCheckAll.isIndeterminate = true;
    } else {
      this.areaCheckAll.checkAll = false;
      this.areaCheckAll.isIndeterminate = false;
    }
  }

  /**
   * 描述 修改区域选择全选状态
   * @param {Object} item 当前编辑的对象
   */
  changeAreaCheckAll(item) {
    item.list.forEach(i => {
      i.isChosen = item.checkAll;
    });
    item.isIndeterminate = false;
  }

  /**
   * 描述 区域下街道选择改变时需要更新区域状态
   * @param {Object} item 当前编辑的对象
   */
  changeAreaCheckItem(item) {
    let count = 0;
    item.list.forEach(i => {
      i.isChosen ? count++ : (count = count);
    });
    if (count === item.list.length) {
      item.checkAll = true;
      item.isIndeterminate = false;
    } else if (count === 0) {
      item.checkAll = false;
      item.isIndeterminate = false;
    } else {
      item.checkAll = false;
      item.isIndeterminate = true;
    }
  }

  /**
   * 描述 最外层全选操作
   */
  changeAreaListAll() {
    this.areaCheckAll.isIndeterminate = false;
    const list = this.areaList.filter(
      i => i.id === this.currentLineId || i.id === "-1",
    );
    list.forEach(i => {
      i.list.forEach(t => {
        t.list.forEach(d => {
          d.isChosen = this.areaCheckAll.checkAll;
        });
        this.changeAreaCheckItem(t);
      });
    });
  }

  /**
   * 描述 确认保存投放区域
   */
  areasIsReady() {
    const ids = [];
    let count = 0;
    let total = 0;
    let list = [];
    if (this.currentLineId === "-1") {
      list = this.areaList.filter(i => i.id !== "-1");
    } else {
      list = this.areaList.filter(
        i => i.id === this.currentLineId || i.id === "-1",
      );
    }
    list.forEach(i => {
      i.list.forEach(t => {
        t.list.forEach(d => {
          if (d.isChosen) {
            ids.push(d.id);
            count++;
          }
          total++;
        });
      });
    });
    if (!ids.length && this.dialogType === 2 && !this.autoStatue) {
      this.$message.error(
        this.isPointSet ? "至少选择一个提货点" : "至少选择一条，请选择！",
      );
      return false;
    }
    this.syncAutoShippingState = this.autoStatue;
    this.emitAreaChoosed({
      ids,
      range: `${count}/${total}`,
    });
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/logistics/putArea.scss";
</style>
<style lang="scss">
.putarea {
  .el-dialog__body {
    font-size: 12px;
  }
  .el-button--text {
    color: #606271;
  }
}
.putarea__table {
  .el-table,
  .el-table__body-wrapper {
    overflow: inherit;

    thead {
      tr,
      th {
        background-color: rgb(246, 248, 250) !important;
      }
    }
  }
}
.putarea__row--aname {
  display: inline-block;
  vertical-align: middle;
  max-width: 110px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
